﻿using UnityEngine;
using System.Collections;
/// <summary>
/// 此脚本添加在门栓上，用于控制门的开关
/// </summary>
public class DoorControler : MonoBehaviour {
	[SerializeField] Transform door;
	[SerializeField] Transform axis;
	[SerializeField] float minDis = 3f;
	[SerializeField] float rotateSpeed = 45f;
	[SerializeField] float maxAngle = 105f;
	[SerializeField] float regionAngle = 0f;
	/// 控制门的开关方向
	[SerializeField] bool openDirection = false;
	float curSpeed;
	float totalAngle=0f;
	bool isDoorOpened = false;
	Coroutine curIE;
	bool isLock = false;

	protected bool IsClosed{
		get{ return (totalAngle < 0f);}
	}

	///开门的次数
	[HideInInspector] public int openTime = 0;

	void Awake(){
		totalAngle = regionAngle;
	}

	/// <summary>
	/// 交互函数，当物体与玩家产生交互时
	/// </summary>
	/// <param name="hit">Hit.</param>
	protected virtual void OnInteraction(RaycastHit hit){
		if (hit.distance < minDis) {
			changeDoorStatus ();
		}
	}

	public void changeDoorStatus(){
		isDoorOpened = isDoorOpened ? closeDoor () : openDoor ();
		print ("isDoorOpened : "+isDoorOpened.ToString());
	}

	public void OpenDoor(){
		isDoorOpened = openDoor ();
	}

	bool openDoor(){
		if (isLock) {
			Debug.Log ("The door is locked");
			return false;
		}
		openTime += 1;
		Debug.Log ("openTime = " + openTime.ToString ());

		curSpeed = rotateSpeed;
		if (curIE != null) {
			StopCoroutine (curIE);
		}
		curIE = StartCoroutine (doorOpenning (curSpeed));
		return true;
	}
	IEnumerator doorOpenning(float openSpeed){
		float angle = openSpeed * Time.deltaTime;
		while (totalAngle < maxAngle) {
			doorRotate(angle);
			yield return null;
		}
		yield return null;
	}
	bool closeDoor(){
		curSpeed = rotateSpeed;
		if (curIE != null) {
			StopCoroutine (curIE);
		}
		curIE = StartCoroutine (doorClosing (-curSpeed));
		return false;
	}
	IEnumerator doorClosing(float closeSpeed){
		float angle = closeSpeed * Time.deltaTime;
		while (totalAngle >= 0f) {
			doorRotate(angle);
			yield return null;
		}
		yield return null;
	}
	void doorRotate(float angle){
		totalAngle += angle;
		angle = openDirection ? -angle : angle;
		door.RotateAround (axis.transform.position, axis.transform.up, angle);
	}

	public void closeDoorSuddenly(bool setLock = true){
		StartCoroutine (doorClosing (-rotateSpeed*5f));
		isDoorOpened = false;
		isLock = setLock;
	}
	public void lockDoor(){
		isLock = true;
		closeDoor ();
	}
	public void unlockDoor(){
		isLock = false;
	}

	[SerializeField] bool testOpenClose = false;
	void Update(){
		if (testOpenClose) {
			testOpenClose = false;
			changeDoorStatus ();
		}
	}
}
